package com.liwy3.thread;

import lombok.SneakyThrows;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Copyright © 2022年10月19日 北京自如信息科技有限公司. All rights reserved.
 *
 * @Prject: liwy3
 * @Package: com.liwy3.thread
 * @Description: 某电影院目前正在上映国产大片，共有100张票，而它有3个窗口卖票，请设计一个程序模拟该电影院卖票
 * @author: Crazy4J
 * @date: 2022年10月19日 10:06
 * @version: V1.0
 */
public class SellTicketSynchronized {

    public static void main(String[] args) {
        //创建三个线程
        int ticketNum = 3;
        ExecutorService executorService = Executors.newFixedThreadPool(ticketNum);
        TicketWorker ticketWorker = new TicketWorker();
        //执行售票逻辑
        try {
            for (int i = 0; i < ticketNum; i++) {
                executorService.execute(ticketWorker);
            }
        } finally {
            executorService.shutdown();
        }

    }

    static class TicketWorker implements Runnable {

        private int ticketNum = 100;

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                synchronized (this) {
                    if (ticketNum > 0) {
                        Thread.sleep(10);
                        ticketNum--;
                        System.out.println(Thread.currentThread().getName() + "当前票数剩余：" + ticketNum);
                    }
                }
                if (ticketNum <= 0) {
                    System.out.println(Thread.currentThread().getName() + "售票结束");
                    break;
                }
            }
        }
    }


}
